import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import { Popup } from 'devextreme-react/popup';
import TextBox from 'devextreme-react/text-box';
import { intl } from '@/utils';
import notify from 'devextreme/ui/notify';
import PTextBox from '@/pages/components/PTextBox';

/**
 * 输入对话框 组件 继承 Dev 的 Popup
 * @param props 
 * @returns
 * 遗留问题
 * 1、默认获取焦点
 * 2、回车既确定 
 */
export interface InputBoxProps {
  args?: {
    title?: string;
    value?: any; // 默认值
    dbname?: any;
    width?: number | string | (() => number | string);
    height?: number | string | (() => number | string);
  }
  onOK: (v: any) => void;
  onCancel?: () => void;
}


const InputDialog = React.forwardRef((props: any, ref: any) => {

  const [diaShow, setDiaShow] = useState<boolean>(false);
  const valueRef = useRef('');
  const paramsRef = useRef<any>();
  const [valueText, setValueText] = useState<any>('');


  useImperativeHandle(ref, () => ({
    show: (params: InputBoxProps) => {
      paramsRef.current = params;
      console.log(params, paramsRef.current, '@@@');
      setValueText(params?.args?.value);
      valueRef.current = params?.args?.value;
      setDiaShow(true);
      // setTimeout(() => {
      //   if (pTextBoxRef.current) {
      //     pTextBoxRef.current.focusTextBox();
      //   }
      // }, 150);
    }
  }));

  const cancel = () => {
    if (paramsRef.current.onCancel) {
      paramsRef.current.onCancel();
    };
    setDiaShow(false);
    setValueText('');
    valueRef.current = '';
  };


  const ok = () => {
    const tempValue = valueRef.current || valueText || '';
    let reg = /^[\s\S]*.*[^\s][\s\S]*$/;
    if (reg.test(tempValue)) {
      setDiaShow(false);
      paramsRef.current.onOK(tempValue);
      setValueText('');
      valueRef.current = '';
    } else {
      notify(`${props.title == "重命名" || "附件重命名" ? '名称不能为空' : '文件夹名称不能为空'}`, 'warning', 2000)
    }
  }

  return <>
    <Popup
      visible={diaShow}
      onHiding={() => cancel()}
      title={paramsRef.current?.args?.title || ""}
      showTitle={true}
      width={paramsRef.current?.args?.width || 380}
      height={paramsRef.current?.args?.height || 200}
      contentRender={() => <PTextBox defaultValue={valueText || ''}
        changeData={(data: any) => {
          setValueText(data);
          valueRef.current = data;
        }}
        onKeyDownTextBox={ok}
      />}
      toolbarItems={[
        {
          widget: "dxButton",
          toolbar: "bottom",
          location: "after",
          options: {
            text: intl('pub.cancel', '取消'),
            onClick: () => cancel()
          }
        },
        {
          widget: "dxButton",
          toolbar: "bottom",
          location: "after",
          options: {
            text: intl('pub.ok', '确定'),
            type: 'default',
            onClick: () => {
              ok();
            }
          }
        },

      ]}
    />
  </>;
});

export default InputDialog;
